package com.ayf.payment.game.api.controller.paychannel;

import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.channel.jiabei.util.JbStringUtil;
import com.ayf.payment.game.api.channel.jiabei.util.StringHelper;
import com.ayf.payment.game.api.dto.platform.PaymentChannelDTO;
import com.ayf.payment.game.api.entity.Order;
import com.ayf.payment.game.api.type.OrderStatus;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.ayf.payment.game.api.wx.WxSendMsgUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 嘉贝支付回调
 *
 * @author wwl
 * @description:
 * @date 2020/5/11 19:22
 */
@RequestMapping("/v/jb/pay")
@RestController
public class JBPayNotifyController extends BasePayNotifyController {
    @Autowired
    private WxSendMsgUtils wxSendMsgUtils;
    /**
     * 嘉贝同步异步通知处理
     */
    @RequestMapping("/notify")
    public void notify(HttpServletRequest request, HttpServletResponse response) {
        String TradeNum = JbStringUtil.formatString(request.getParameter("TradeNum"));      // 商户订单号 您的网站订单号
        super.notifyAsync(request,response,TradeNum);
    }


    @Override
    protected void notifyAsyncBusinesExec(HttpServletRequest request, HttpServletResponse response,Object obj) {
        PrintWriter pw = null;
        String traceId = SnowFlakeUtils.getTraceId();
        try {
            pw = response.getWriter();
            //获取参数
            String Amount = JbStringUtil.formatString(request.getParameter("Amount"));        //金额 该笔订单的资金总额，单位为RMB。取值范围为[1,10000000.00]。
            String ApiMethod = "OnLinePay";                                         // 业务标识 固定值:OnLinePay
            String Ext1 = JbStringUtil.formatString(request.getParameter("Ext1"));          //商户扩展信息 交易请求时上传，通知原样返回
            String OrderNum = JbStringUtil.formatString(request.getParameter("OrderNum"));      // 系统订单号 【支付平台】订单号
            String PayType = JbStringUtil.formatString(request.getParameter("PayType"));       // 支付方式
            String RespCode = JbStringUtil.formatString(request.getParameter("RespCode"));      // 响应代码 请求处理状态1111：处理成功 2222：处理失败
            String ResultCode = JbStringUtil.formatString(request.getParameter("ResultCode"));    //业务处理代码 固定值：101
            String SignType = JbStringUtil.formatString(request.getParameter("SignType"));      // 签名方式
            String Status = JbStringUtil.formatString(request.getParameter("Status"));        // 状态码 订单支付状态: 01:支付成功 02：待支付
            String TradeNum = JbStringUtil.formatString(request.getParameter("TradeNum"));      // 商户订单号 您的网站订单号
            String Version = "V2.0";                                              // 版本号 固定值:V2.0
            String Sign = JbStringUtil.formatString(request.getParameter("Sign"));          // 签名数据
            if (StringUtils.isEmpty(TradeNum)) {
                LogPortal.info("{} 嘉贝交易异步通知 商户订单号数值为空，不进行后续操作", traceId);
                pw.write("ERROR订单未支付成功");
                pw.flush();
                return;
            }
            Order order = orderService.selectByMerchantOrderNo(TradeNum);
            if (order == null) {
                LogPortal.error("{} 嘉贝交易异步通知 订单号[{}]在我方系统查询不到", traceId, TradeNum);
                pw.write("ERROR订单未支付成功");
                pw.flush();
                return;
            }
            PaymentChannelDTO paymentChannelDTO = systemInitialization.channelDTO(order.getPayChannleId());
            //商户编号
            String MerhantId = paymentChannelDTO.getAccountNumber();
            //测试商户密钥
            String KeyValue = paymentChannelDTO.getChannelKey();
            //生成签名
            HashMap<String, String> dicMap = new HashMap<String, String>();
            dicMap.put("Amount", Amount);
            dicMap.put("ApiMethod", ApiMethod);
            dicMap.put("Ext1", Ext1);
            dicMap.put("MerID", MerhantId);
            dicMap.put("OrderNum", OrderNum);
            dicMap.put("PayType", PayType);
            dicMap.put("RespCode", RespCode);
            dicMap.put("ResultCode", ResultCode);
            dicMap.put("SignType", SignType);
            dicMap.put("Status", Status);
            dicMap.put("TradeNum", TradeNum);
            dicMap.put("Version", Version);
            SortedMap<String, String> sortMap = new TreeMap<String, String>(dicMap);
            String signData = StringHelper.createSign(sortMap);
            String signVer = StringHelper.EncodeMD5(signData + "key=" + KeyValue);
            signVer = signVer.toLowerCase();
            if (Sign.trim().equals(signVer.trim())) {
                if ("01".equals(Status)) {
                    if (OrderStatus.PROCESSING.equals(order.getOrderStatus())) {
                        order.setOrderNo(OrderNum);
                        order.setOrderStatus(OrderStatus.SUCCESS);
                        orderService.paymentOrder(order, new JSONObject());
                        if (OrderStatus.SUCCESS.equals(order.getOrderStatus())) {
                            orderService.orderToGetWay(order);
                            try {
                                wxSendMsgUtils.rechargeSuccess(order);
                            } catch (Exception e) {
                                LogPortal.error("{} 嘉贝交易异步通知 商户订单号[{}]CallBack 微信通知异常", e, traceId, OrderNum);
                            }
                        }
                    }else{
                        LogPortal.info("{} 嘉贝交易异步通知 商户订单号[{}] 异步通知 不在更新订单状态：[{}]", traceId, OrderNum,order.getOrderStatus());
                    }
                    pw.write("SUCCESS");
                    pw.flush();
                } else {
                    pw.write("ERROR订单未支付成功");
                    pw.flush();
                }
            } else {
                LogPortal.error("{} 嘉贝交易异步通知 商户订单号[{}] 异步通知验签失败", traceId, TradeNum);
                pw.write("ERROR验签处理失败");
                pw.flush();
            }
        } catch (Exception e) {
            LogPortal.error("{} 嘉贝交易异步通知 业务逻辑处理失败，具体原因:{}", e, traceId, e.getMessage());
            pw.write("ERROR订单未支付成功");
            pw.flush();
        } finally {
            if (pw != null)
                pw.close();
        }
    }

    @Override
    protected void notifySyncBusinesExec(HttpServletRequest request, HttpServletResponse response) {

    }

    @Override
    protected void agentPayNotifyAsyncBusinesExec(HttpServletRequest request, HttpServletResponse response, Object obj) {

    }
}
